const router = require("koa-router")();
const fse = require("fs-extra");
const uuid = require("uuid/v4");
const moment = require("moment");
const path = require("path");
const Jimp = require("jimp");
const util = require("./../util/util");

router.post("/class/:className/image/upload", async (ctx, next) => {
  const { className } = ctx.params;

  // 数据表访问权限验证
  ctx.classTable = await BaaS.Models.classTable
    .query({
      where: {
        baas_id: ctx.baas.id,
        class_id: ctx.class.id,
        table: "baas.file"
      }
    })
    .fetch({
      withRelated: ["secret"],
      withRedisKey: ctx.getAppKey(
        `class:${className}:table:baas.file:classTable`
      )
    });
  if (!ctx.classTable) {
    ctx.status = 401;
    throw new Error(`Class ${className} Image Upload Unauthorized`);
  }

  // 检测是否上传文件
  if (!ctx.file && !ctx.file.file) {
    throw new Error("Upload Image Error");
  }

  const file = ctx.file.file;
  const key = `lock:image:upload:url:${ctx.url}:name:${file.name}:type:${
    file.type
  }:size:${file.size}`;
  const locked = await BaaS.redis.lock(key);
  if (locked) {
    let ext = ""; // 后缀名
    switch (file.type) {
      case "image/jpg":
        ext = "jpg";
        break;
      case "image/pjpeg":
        ext = "jpg";
        break;
      case "image/jpeg":
        ext = "jpg";
        break;
      case "image/png":
        ext = "png";
        break;
      case "image/x-png":
        ext = "png";
      case "image/gif":
        ext = "gif";
        break;
    }
    if (!ext) {
      await fse.remove(file.path);
      ctx.error(`Upload Image Error File Type ${file.type} Don\`t Support`);
      return;
    }

    const savepath = moment().format("YYYY-MM-DD");
    const savename = uuid() + "." + ext;

    // 存数据库
    await BaaS.Models.file
      .forge({
        baas_id: ctx.baas.id,
        name: file.name,
        ext: ext,
        type: file.type,
        size: file.size,
        savename: savename,
        savepath: savepath
      })
      .save();

    // 上传七牛
    if (util.config("qiniu")) {
      const imageUrl = await util.uploadFile(file.path, savename);
      if (ctx.query.type === "1") {
        ctx.body = `http://img1.qingful.com/${imageUrl}`;
      } else {
        ctx.success(`${imageUrl}`, "success");
      }
    } else {
      // 上传本地
      await fse.move(
        file.path,
        path.resolve("www/uploads", savepath, savename)
      );

      // 图片压缩 质量 30
      Jimp.read(path.resolve("www/uploads/", savepath, savename))
        .then(lenna => {
          lenna
            .quality(30)
            .write(path.resolve("www/uploads/", savepath, savename));
        })
        .catch(err => {
          console.error(err);
        });

      ctx.success(
        `https://${ctx.host}/uploads/${savepath}/${savename}`,
        "success"
      );
    }

    await BaaS.redis.unlock(key);
  } else {
    console.log(`${key} Waiting`);
  }
});

module.exports = router;
